package com.ruoyi.web.controller.module.event;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.service.module.estate.IEstateBuildService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 计划任务：人员计划记录Controller
 *
 * @author ruoyi
 * @date 2023-12-25
 */
@Validated
@Api(value = "计划任务：人员计划记录控制器", tags = {"计划任务：人员计划记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/task")
public class EventPlanTaskController extends BaseController {

    private final IEventPlanTaskService eventPlanTaskService;
	private final ISysUserService sysUserService;
	private final IEstateService estateService;
	private final IPropertyService propertyService;
	private final IEventPlanService eventPlanService;
	private final IEventTerminalGroupService eventTerminalGroupService;
	private final IEventCleanAreaService eventCleanAreaService;
	private final IEventCleanAreaListService eventCleanAreaListService;
	private final IEstateBuildService estateBuildService;
	private final IEventPatrolLineService eventPatrolLineService;
	private final IEventPlanWorkService eventPlanWorkService;
    /**
     * 查询计划任务：人员计划记录列表
     */
    @ApiOperation("查询计划任务：人员计划记录列表")
    @PreAuthorize("@ss.hasPermi('module:planTask:list')")
    @GetMapping("/list")
    public TableDataInfo<EventPlanTask> list(@Validated EventPlanTask eventPlanTask) {
		SysUser sysUser = getUser();

		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPlanTask.getPropertyId() != null){
				qw.eq("property_id",eventPlanTask.getPropertyId());
			}
			if(eventPlanTask.getEstateId() != null){
				qw.eq("estate_id",eventPlanTask.getEstateId());
			}
		}
		if (eventPlanTask.getEventPlanId()!=null){
			qw.eq("event_plan_id",eventPlanTask.getEventPlanId());
		}
		if(eventPlanTask.getEventType()!=null){
			qw.eq("event_type",eventPlanTask.getEventType());
		}
		if(eventPlanTask.getState()!=null){
			qw.eq("state",eventPlanTask.getState());
		}
		if (eventPlanTask.getWorkId()!=null){
			qw.eq("work_id",eventPlanTask.getWorkId());
		}
		qw.orderByDesc("begin_time");
        TableDataInfo<EventPlanTask> td = PageUtils.buildDataInfo(eventPlanTaskService.page(PageUtils.buildPage(),qw));
        List<EventPlanTask> list = td.getRows();
		for (EventPlanTask list1:list){
			if (list1.getPropertyId()!=null){
				list1.setPropertyName(propertyService.findById(list1.getPropertyId()).getPropertyName());
			}
			if(list1.getEstateId()!=null){
				list1.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
			if (list1.getEventPlanId()!=null){
				list1.setPlanName(eventPlanService.findById(list1.getEventPlanId()).getPlanTitle());
			}
			if (list1.getEventType() == 1) {
				if (list1.getEventTargetId()!=null){
					if (list1.getEventTargetId()==0){
						list1.setGroupName("设备组");
					}else {
						list1.setGroupName(eventTerminalGroupService.findById(list1.getEventTargetId()).getGroupName());
					}
				}
			}
			if(list1.getEventType() == 3 || list1.getEventType() == 4){
				list1.setGroupName(eventCleanAreaListService.findById(list1.getEventTargetId()).getAreaName());
			}
		}
        return td;
    }
	@ApiOperation("查询计划任务：人员计划记录列表")
	@PreAuthorize("@ss.hasPermi('module:planTask:list')")
	@GetMapping("/count")
	public EventPlanCount count(@Validated EventPlanTask eventPlanTask) {
		EventPlanCount count = new EventPlanCount();
		SysUser sysUser = getUser();
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		if (eventPlanTask.getEventType()!=null){
			qw.eq("event_type",eventPlanTask.getEventType());
		}
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPlanTask.getPropertyId() != null){
				qw.eq("property_id",eventPlanTask.getPropertyId());
			}
			if(eventPlanTask.getEstateId() != null){
				qw.eq("estate_id",eventPlanTask.getEstateId());
			}
		}
		if (eventPlanTask.getEndTime()!=null){
			qw.between("end_time",eventPlanTask.getBeginTime() + " 00:00:00",eventPlanTask.getEndTime() + " 23:59:59");
		}
		List<EventPlanTask> taskList = eventPlanTaskService.list(qw);
		qw.ne("state",4);
		qw.groupBy("worker_sys_user_id");
		List<EventPlanTask> userList = eventPlanTaskService.list(qw);
//		count.setPlanCount(taskList.size());
		count.setUserCount(userList.size());
		EventPlanUserCount eventPlanUserCount = new EventPlanUserCount();
		List<EventPlanUserCount> userCountList = new ArrayList<>();

		List<EventPlanUserCountInfo> yiwanchengListAll = new ArrayList<>();

		for (EventPlanTask user:userList){
			List<EventPlanUserCountInfo> yiwanchengs = new ArrayList<>();
			EventPlanUserCount count1 = new EventPlanUserCount();
			count1.setRealName(user.getWorkerName());
			int weiwancheng = 0;
			int jinxingzhong = 0;
			int yiwancheng = 0;
			int renwu = 0;
			for (EventPlanTask task:taskList){
				//总统计表
				//统计任务数
				if (user.getWorkerSysUserId().equals(task.getWorkerSysUserId())){
					if (task.getState()==0){
						weiwancheng+=1;
					}
					if (task.getState()==1){
						jinxingzhong+=1;
					}
					if (task.getState()==2){
						yiwancheng+=1;
						renwu+=1;
						EventPlanUserCountInfo info = new EventPlanUserCountInfo();
						info.setPlanName(eventPlanService.findById(task.getEventPlanId()).getPlanTitle());
						if (task.getEventType()==1){
							info.setTaskInfoName(eventTerminalGroupService.findById(task.getEventTargetId()).getGroupName());
						}else if (task.getEventType()==2){
							info.setTaskInfoName(eventPatrolLineService.findById(task.getEventTargetId()).getLineName());
						}else if(task.getEventType()==3||task.getEventType()==4||task.getEventType()==5){
							info.setTaskInfoName(eventCleanAreaListService.findById(task.getEventTargetId()).getAreaName());
						}
						info.setRealName(task.getWorkerName());
						info.setEndTime(task.getHandleTime());
						yiwanchengs.add(info);
					}
				}
			}
			for (EventPlanUserCountInfo info:yiwanchengs){
				info.setCompleted(renwu);
				yiwanchengListAll.add(info);
			}
			count1.setBegan(weiwancheng);
			count1.setAfoot(jinxingzhong);
			count1.setCompleted(yiwancheng);
			count1.setCount(weiwancheng+yiwancheng+jinxingzhong);
			userCountList.add(count1);
		}
		count.setUserPlanInfoList(yiwanchengListAll);
		count.setUserPlanList(userCountList);
		QueryWrapper<EventPlan> qwPlan = new QueryWrapper<>();
		if (eventPlanTask.getEventType()!=null){
			qwPlan.eq("event_type_id",eventPlanTask.getEventType());
		}
		List<EventPlan> planList = eventPlanService.list(qwPlan);
		int weiwancheng = 0;
		int yiwancheng = 0;
		int jinxingzhong = 0;
		for (EventPlan plan : planList){
			//查询未完成总数
			QueryWrapper<EventPlanWork> qw1 = new QueryWrapper<>();
			if (plan.getId()!=null){
				qw1.eq("event_plan_id",plan.getId());
			}
			if(sysUser.getUserType() == 2){
				qw1.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){
				qw1.eq("estate_id",sysUser.getEstateId());
			}else{
				if(eventPlanTask.getPropertyId() != null){
					qw1.eq("property_id",eventPlanTask.getPropertyId());
				}
				if(eventPlanTask.getEstateId() != null){
					qw1.eq("estate_id",eventPlanTask.getEstateId());
				}
			}
			if (eventPlanTask.getEndTime()!=null){
				qw1.between("end_time",eventPlanTask.getBeginTime() + " 00:00:00",eventPlanTask.getEndTime() + " 23:59:59");
			}
			qw1.eq("state",0);
			List<EventPlanWork> weiwanchengList = eventPlanWorkService.list(qw1);
			weiwancheng+=weiwanchengList.size();

			//查询进行中总数
			QueryWrapper<EventPlanWork> qw2 = new QueryWrapper<>();
			if (plan.getId()!=null){
				qw2.eq("event_plan_id",plan.getId());
			}
			if(sysUser.getUserType() == 2){
				qw2.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){
				qw2.eq("estate_id",sysUser.getEstateId());
			}else{
				if(eventPlanTask.getPropertyId() != null){
					qw2.eq("property_id",eventPlanTask.getPropertyId());
				}
				if(eventPlanTask.getEstateId() != null){
					qw2.eq("estate_id",eventPlanTask.getEstateId());
				}
			}
			if (eventPlanTask.getEndTime()!=null){
				qw2.between("end_time",eventPlanTask.getBeginTime() + " 00:00:00",eventPlanTask.getEndTime() + " 23:59:59");
			}
			qw2.eq("state",1);
			List<EventPlanWork> jinxingzhongList = eventPlanWorkService.list(qw2);
			jinxingzhong+=jinxingzhongList.size();

			//查询已完成总数
			QueryWrapper<EventPlanWork> qw3 = new QueryWrapper<>();
			if (plan.getId()!=null){
				qw3.eq("event_plan_id",plan.getId());
			}
			if(sysUser.getUserType() == 2){
				qw3.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){
				qw3.eq("estate_id",sysUser.getEstateId());
			}else{
				if(eventPlanTask.getPropertyId() != null){
					qw3.eq("property_id",eventPlanTask.getPropertyId());
				}
				if(eventPlanTask.getEstateId() != null){
					qw3.eq("estate_id",eventPlanTask.getEstateId());
				}
			}
			if (eventPlanTask.getEndTime()!=null){
				qw3.between("end_time",eventPlanTask.getBeginTime() + " 00:00:00",eventPlanTask.getEndTime() + " 23:59:59");
			}
			qw3.eq("state",2);
			List<EventPlanWork> yiwanchengList = eventPlanWorkService.list(qw3);
			yiwancheng+=yiwanchengList.size();

		}
		count.setBegan(weiwancheng);
		count.setAfoot(jinxingzhong);
		count.setCompleted(yiwancheng);
		count.setPlanCount(count.getCompleted()+count.getAfoot()+count.getBegan());
		return count;
	}
    /**
     * 导出计划任务：人员计划记录列表
     */
    @ApiOperation("导出计划任务：人员计划记录列表")
    @PreAuthorize("@ss.hasPermi('module:planTask:export')")
    @Log(title = "计划任务：人员计划记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventPlanTask> export(@Validated EventPlanTask eventPlanTask) {
		SysUser sysUser = getUser();

		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPlanTask.getPropertyId() != null){
				qw.eq("property_id",eventPlanTask.getPropertyId());
			}
			if(eventPlanTask.getEstateId() != null){
				qw.eq("estate_id",eventPlanTask.getEstateId());
			}
		}
		if (eventPlanTask.getEventPlanId()!=null){
			qw.eq("event_plan_id",eventPlanTask.getEventPlanId());
		}
		if(eventPlanTask.getEventType()!=null){
			qw.eq("event_type",eventPlanTask.getEventType());
		}
		if(eventPlanTask.getState()!=null){
			qw.eq("state",eventPlanTask.getState());
		}
		if (eventPlanTask.getWorkId()!=null){
			qw.eq("work_id",eventPlanTask.getWorkId());
		}
		qw.orderByDesc("begin_time");
		List<EventPlanTask> list = eventPlanTaskService.list(qw);
		for (EventPlanTask list1:list){
			if (list1.getPropertyId()!=null){
				list1.setPropertyName(propertyService.findById(list1.getPropertyId()).getPropertyName());
			}
			if(list1.getEstateId()!=null){
				list1.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
			if (list1.getEventPlanId()!=null){
				list1.setPlanName(eventPlanService.findById(list1.getEventPlanId()).getPlanTitle());
			}
			// 查询执行计划名称
			//	巡检
			if (list1.getEventType() == 1){
				EventTerminalGroup group = eventTerminalGroupService.findById(list1.getEventTargetId());
				list1.setGroupName(group.getGroupName());
			}
			//	巡更
			if (list1.getEventType() == 2){
				EventPatrolLine line = eventPatrolLineService.findById(list1.getEventTargetId());
				list1.setGroupName(line.getLineName());
			}
			//	保洁
			if (list1.getEventType() == 3){
				EventCleanArea area = eventCleanAreaService.findById(list1.getEventTargetId());
				list1.setGroupName(area.getAreaTitle());
			}
			if (list1.getBeginTime()!=null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				list1.setBeginTimes(sdf.format(list1.getBeginTime()));
			}
			if (list1.getEndTime()!=null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				list1.setEndTimes(sdf.format(list1.getEndTime()));
			}
			if (list1.getEventType() == 1) {
				if (list1.getEventTargetId()!=null){
					if (list1.getEventTargetId()==0){
						list1.setGroupName("设备组");
					}else {
						list1.setGroupName(eventTerminalGroupService.findById(list1.getEventTargetId()).getGroupName());
					}
				}
			}
			if(list1.getEventType() == 3 || list1.getEventType() == 4){
				list1.setGroupName(eventCleanAreaService.findById(list1.getEventTargetId()).getAreaTitle());
			}
		}
        ExcelUtil<EventPlanTask> util = new ExcelUtil<EventPlanTask>(EventPlanTask.class);
        return util.exportExcel(list, "计划任务：人员计划记录");
    }

    /**
     * 获取计划任务：人员计划记录详细信息
     */
    @ApiOperation("获取计划任务：人员计划记录详细信息")
    @PreAuthorize("@ss.hasPermi('module:planTask:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventPlanTask> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventPlanTask eventPlanTask = eventPlanTaskService.getById(id);
        return AjaxResult.success(eventPlanTask);
    }

    /**
     * 新增计划任务：人员计划记录
     */
    @ApiOperation("新增计划任务：人员计划记录")
    @PreAuthorize("@ss.hasPermi('module:planTask:add')")
    @Log(title = "计划任务：人员计划记录", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventPlanTask eventPlanTask) {
		if (eventPlanTask.getWorkerSysUserId()!=null){
			SysUser sysUser = sysUserService.selectUserById(Long.valueOf(eventPlanTask.getWorkerSysUserId()));
			if (sysUser!=null){
				if (sysUser.getPhoneNum()!=null){
					eventPlanTask.setWorkerPhone(sysUser.getPhoneNum());
				}
				if (sysUser.getWxUserId()!=null){
					eventPlanTask.setWorkerWxUserId(sysUser.getWxUserId());
				}
				if (sysUser.getNickName()!=null){
					eventPlanTask.setWorkerName(sysUser.getNickName());
				}
			}
		}
        return toAjax(eventPlanTaskService.save(eventPlanTask) ? 1 : 0);
    }

    /**
     * 修改计划任务：人员计划记录
     */
    @ApiOperation("修改计划任务：人员计划记录")
    @PreAuthorize("@ss.hasPermi('module:planTask:edit')")
    @Log(title = "计划任务：人员计划记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventPlanTask eventPlanTask) {
		if (eventPlanTask.getWorkerSysUserId()!=null){
			SysUser sysUser = sysUserService.selectUserById(Long.valueOf(eventPlanTask.getWorkerSysUserId()));
			if (sysUser!=null){
				if (sysUser.getPhoneNum()!=null){
					eventPlanTask.setWorkerPhone(sysUser.getPhoneNum());
				}
				if (sysUser.getWxUserId()!=null){
					eventPlanTask.setWorkerWxUserId(sysUser.getWxUserId());
				}
				if (sysUser.getNickName()!=null){
					eventPlanTask.setWorkerName(sysUser.getNickName());
				}
			}
		}
        return toAjax(eventPlanTaskService.updateById(eventPlanTask) ? 1 : 0);
    }

    /**
     * 删除计划任务：人员计划记录
     */
    @ApiOperation("删除计划任务：人员计划记录")
    @PreAuthorize("@ss.hasPermi('module:planTask:remove')")
    @Log(title = "计划任务：人员计划记录" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(eventPlanTaskService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
